package com.llh.cheap.configs;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:database.properties")
public class DatabaseConfig {

    @Bean
    @Qualifier("MAIN_TM")
    public DataSourceTransactionManager transactionManager(@Qualifier("MAIN_DS") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Qualifier("MAIN_TT")
    public TransactionTemplate transactionTemplate(@Qualifier("MAIN_TM") DataSourceTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }

    @Bean
    @Qualifier("MAIN_DB")
    public JdbcTemplate db(@Qualifier("MAIN_DS") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    @Qualifier("MAIN_NAMED_DB")
    public NamedParameterJdbcTemplate namedDB(@Qualifier("MAIN_DS") DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }

    @Bean
    @Qualifier("MAIN_DS")
    public DataSource dataSource(
            @Value("${db.url}") String dbURL,
            @Value("${db.user}") String dbUser,
            @Value("${db.password}") String dbPassword,
            @Value("${db.pool_name}") String dbPoolName,
            @Value("${db.pool_size}") int dbPoolSize
    ) {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(dbURL);
        config.setUsername(dbUser);
        config.setPassword(dbPassword);
        config.setPoolName(dbPoolName);
        config.setMaximumPoolSize(dbPoolSize);
        config.setMaxLifetime(30000);
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.setAutoCommit(true);
        return new HikariDataSource(config);
    }

}
